package com.erb.service.zwj.impl;

import com.erb.constants.AdminIntegralGoodsConstants;
import com.erb.entity.IntegralGoods;
import com.erb.mapper.IntegralGoodsMapper;
import com.erb.service.zwj.IIntegralGoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Transactional
@Service("integralGoodsService")
public class IIntegralServiceImpl implements IIntegralGoodsService {
	@Resource
	private IntegralGoodsMapper integralGoodsMapper;

	@Override
	public List<IntegralGoods> findAllGoodsForList() {
		return integralGoodsMapper.findGoodsForList();
	}

	@Override
	public IntegralGoods findGoodsById(Integer id) {
		if (ObjectUtils.isEmpty(id)) {
			return null;
		}
		return id > 0 ? integralGoodsMapper.findGoodsById(id) : null;
	}

	@Override
	public boolean save(IntegralGoods integralGoods) {
		if (integralGoods.getType().equals(AdminIntegralGoodsConstants.INTEGRAL_GOODS_TYPE_ENTITY)) {
			// 保存的商品实物，不需要金额
			integralGoods.setMoney(null);
		}
		integralGoods.setState(AdminIntegralGoodsConstants.INTEGRAL_GOODS_DETAULT_STATE);

		// 保存数据库
		return integralGoodsMapper.saveIntegralGoods(integralGoods) > 0;
	}

	@Override
	public boolean modify(IntegralGoods integralGoods) {
		if (ObjectUtils.isEmpty(integralGoods.getId())) {
			return false;
		}
		if (integralGoods.getType().equals(AdminIntegralGoodsConstants.INTEGRAL_GOODS_TYPE_ENTITY)) {
			// 保存的商品实物，不需要金额
			integralGoods.setMoney(null);
		}

		// 保存数据库
		return integralGoodsMapper.modifyIntegralGoods(integralGoods) > 0;
	}

	@Override
	public boolean remove(Integer goodsId) {
		if (ObjectUtils.isEmpty(goodsId)) {
			return false;
		}
		return integralGoodsMapper.removeIntegralGoods(goodsId) > 0;
	}

	@Override
	public List<IntegralGoods> findGoodsForListOfPutaway() {
		return integralGoodsMapper.findGoodsForListOfPutaway();
	}

	@Override
	public boolean decrGoodsStock(int id, int decr) {
		if (id <= 0) {
			return false;
		}
		if (decr == 0) {
			return true;
		}
		/*
		查询是否还有库存，为0，不能减少
		 */
		int stock = this.integralGoodsMapper.findStockById(id);
		if (stock <= 0) {
			return false;
		}

		return integralGoodsMapper.modifyGoodsStock((decr > 0 ? -1 * decr : decr), id) > 0;
	}

	@Override
	public boolean modifyGoodsStateById(int id, boolean state) {
		if (id <= 0) {
			return false;
		}
		return integralGoodsMapper.modifyGoodsStateById(id, state) > 0;
	}
}
